import 'package:flutter/widgets.dart';

import '../../logger.dart';
import 'store.dart';

abstract class MobXWidgetState<TWidget extends StatefulWidget,
    TStore extends StoreWithLifecycle> extends State<TWidget> {
  bool _hasInitialized;
  TStore _viewModel;

  TStore get viewModel => _viewModel;

  TStore createStore();

  @override
  void initState() {
    super.initState();
    Logger.d(msg: '$this...MobXWidgetState.initState');
    this._hasInitialized = false;
    this._viewModel = createStore();
    viewModel.onCreate();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    Logger.d(msg: '$this...MobXWidgetState.didChangeDependencies...$context');
    if (!this._hasInitialized) {
      viewModel.onContextAttached(context);
      this._hasInitialized = true;
    }
  }

  @override
  void dispose() {
    super.dispose();
    Logger.d(msg: '$this...MobXWidgetState.dispose');
    viewModel.onContextDetached(context);
    viewModel.onDefunct();
  }

  @override
  void deactivate() {
    super.deactivate();
    Logger.d(msg: '$this...MobXWidgetState.deactivate');
  }

  String get pageName {
    final fullName = this.toString();
    return fullName.substring(0, fullName.indexOf('#'));
  }
}
